package com.reading.message.controller;

import com.reading.common.utils.JsonResult;
import com.reading.common.utils.Md5Util;
import com.reading.common.utils.StringUtil;
import com.reading.message.config.SmsConfig;
import com.reading.message.service.SmsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * 短信API
 */
@Slf4j
@RestController
public class SmsController {

    @Resource
    private SmsConfig smsConfig;

    @Resource
    private SmsService smsService;

    /**
     * 登陆发送短信验证码
     *
     * @param token Md5 32位(手机号+time+密钥串)  密钥：dk-s+%jf$iH#U@G)feqi*&*(239
     */
    @RequestMapping(value = "/sendSmsCode", method = RequestMethod.GET)
    public JsonResult sendSmsCode(@RequestHeader(value = "m", required = false) String mobileNo,
                                  @RequestHeader(value = "time", required = false) String time,
                                  @RequestHeader(value = "t", required = false) String token,
                                  @RequestHeader(value = "ty", required = false) String smsCodeType) {
        if (StringUtil.isEmpty(mobileNo) || StringUtil.isEmpty(time) || StringUtil.isEmpty(token)) {
            log.error("参数不合法,m:{},time:{},t={}", mobileNo, time, token);
            return JsonResult.error(-1, "请求失败");
        }

        String tokenOrign = mobileNo + time + smsConfig.getEncryptKey();
        String tokenN = Md5Util.encrypt(tokenOrign, Md5Util.BitNum.Bit32);
        if (StringUtil.isEmpty(tokenN) || !token.equalsIgnoreCase(tokenN)) {
            log.error("验证失败,m:{},time:{},t={},tn={}", mobileNo, time, token, tokenN);
            return JsonResult.error(-2, "验证失败");
        }
        String smsCode = StringUtil.genRandomNum(6);
        int status = smsService.sendSmsCode(smsCodeType, mobileNo, smsCode);
        if (status == 0) {
            return JsonResult.success("验证码发送成功");
        } else {
            return JsonResult.error(-3, "发送失败");
        }
    }

}
